<template>
  <div class="Registration">
    <div class="list">
      <van-form validate-first>
        <div v-for="(item, index) in labelData" :key="index">
          <!-- <span style="color: #ff0000">*</span> -->
          <van-field
            v-if="!item.isSelect && !item.isTime&&item.label!= '从业年限'&&item.label!= '其他技能'"
            v-model="formData[item.key]"
            :label="item.label"
            :placeholder="'请填写' + item.label"
            :readonly="item.isread"
          />
          <van-field
            v-if="!item.isSelect && !item.isTime&&item.label== '从业年限'&&item.label!= '其他技能'"
            v-model="formData[item.key]"
            :label="item.label"
            :placeholder="'请填写' + item.label"
            :readonly="!iSadd"
          />
          <van-field
            v-if="!item.isSelect && !item.isTime&&item.label!= '从业年限'&&item.label== '其他技能'&&qitaShow"
            v-model="formData[item.key]"
            :label="item.label"
            :placeholder="'请填写' + item.label"
            :readonly="!iSadd"
          />
          <div v-if="item.isSelect && !item.isTime">
            <div v-if="item.label !== '常住地址'&&item.label !== '注册区域'&&item.label !== '技能工种'">
              <van-field
                readonly
                clickable
                name="picker"
                v-model="formData[item.key]"
                :label="item.label"
                :placeholder="'请选择' + item.label"
                @click="formData1[item.key1] = iSadd"
              />
              <van-popup v-model="formData1[item.key1]" position="bottom" get-container="#popup">
                <van-picker
                  show-toolbar
                  :columns="formData2[item.key1]"
                  value-key="DICNAME"
                  @confirm="onConfirm1"
                  @cancel="formData1[item.key1] = false"
                />
              </van-popup>
            </div>
            <div v-else-if="item.label == '技能工种'">
                <van-field
                readonly
                clickable
                name="picker"
                v-model="formData[item.key]"
                :label="item.label"
                :placeholder="'请选择' + item.label"
                @click="VantSelects"
              />
              <vanSelect 
                    ref="selectMulPicker"
                    v-model="selectType"
                    placeholder="请选择"
                    :columns="formData2.workerType"
                    label-width="100"
                    @confirm="confirmMulSelect"
                    :option="{label:'DICNAME', value:'key'}" />
            </div>
            <span class="btn" v-if="item.label == '常住地址'||item.label == '注册区域'">
              <van-field
                readonly
                clickable
                :required="item.isread1"
                name="picker"
                v-model="formData[item.key]"
                :label="item.label"
                :placeholder="'请选择' + item.label"
                @click="handleChange(item.label)"
              />
              <van-popup v-model="IsShowAre" round position="bottom">
                <van-cascader
                  v-model="cascaderValue"
                  title="切换城市"
                  :options="options"
                  @close="closeA"
                  @change="onChange"
                  @finish="onFinish"
                />
              </van-popup>
            </span>
          </div>
          <div v-if="item.isTime">
            <van-field
              readonly
              clickable
              name="picker"
              @click="formData1[item.key1] = iSadd"
              v-model="formData[item.key]"
              :label="item.label"
              :placeholder="'请选择' + item.label"
            />
            <van-popup v-model="formData1[item.key1]" position="bottom">
              <van-datetime-picker
                v-model="currentDate"
                type="date"
                title="选择年月日"
                @cancel="formData1[item.key1] = false"
                @confirm="onConfirm2"
                :min-date="minDate"
                :max-date="maxDate"
              />
            </van-popup>
          </div>
        </div>
        <div>
          <p style="color: #5d5d5d; padding: 10px 14px">
            <span style="color: #ff0000">*</span>
            本人正面照：
          </p>
          <div>
            <div style="width: 50%; float: left; text-align: center">
              <van-uploader
                v-model="fileList"
                :disabled="!iSadd"
                accept="image/jpeg, image/png, image/jpg, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/pdf"
                :after-read="afterRead"
                :deletable="iSadd"
                :before-delete="delectFile"
                :max-count="1"
              >
                <!-- <van-image
                      :src="
                        url
                          ? baseUrl + url
                          : 'https://nf1zjszlb.jst.zj.gov.cn:9601/serverfile/zheliban/icon/ZLJ/sfz1011.png'
                      "
                      width="200"
                      alt=""
                    /> -->
              </van-uploader>
              <p :style="{ fontSize: showEdition ? '12px' : '14px' }">本人正面照</p>
            </div>
          </div>
        </div>
      </van-form>
    </div>
    <div class="footer">
      <van-button type="info" size="normal" style="padding: 6px" @click="getinsertDataView('修改')"
        >我要报名</van-button
      >
    </div>
  </div>
</template>


  <style lang="scss" scoped>
.Registration {
  height: 100vh;
  overflow-y: auto;
  padding: 6px;
  position: relative;
  .list {
    height: 84vh;
    overflow-y: auto;
  }
  .footer {
    position: absolute;
    height: 6vh;
    // bottom: 18px;
    left: 50%;
    top: 94%;
    transform: translate(-50%, -50%);
  }
}
</style>


  <script>
import {
  LoadGridData,
  QuerySignCallback,
  GetAdministrative,
  getDatalistForTree,
  zhejiangHouseArtisan,
  zhejiangHouseArtisanUp,
  dataqueryFile,
  selectListByIds,
  ossUploadFiles,
  osspreviewFiles,
  FileServerProxy,
  zhejiangHouseTrainingEduBysubmit,
  zhejiangHouseArtisanRaceInfo,
  zhejiangHouseTrainingEduBysubmitJS
} from '../../../utils/api'
import { idCard } from '../../../utils/idCard'
import timeFormat from '@/utils/timeFormat.js'
import vanSelect from './vantSelect.vue'
export default {
  data() {
    return {
       selectType:[],
      formData: {
        artisanName: '',
        artisanSex: '',
        artisanEducation: '',
        artisanBirthdate: '',
        contactAddress: '',
        belongArea1: '',
        belongArea:"",
        belongCountry:'',
        artisanSkill: '',
        idCard: '',
        phone: '',
        bookNumber: '',
        workYear: '',
        fileid: '',
        isSkill:'',
        citycode:"",
        otherSkill:'',
      },
      cascaderValue: '',
      options: [
        {
          text: '杭州市',
          value: '441300000000',
          children: [],
        },
      ],
      IsShowAre: false,
      showEdition: true,
      currentDate: new Date(),
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2089, 12, 1),
      isread: false,
      formData1: {
        sex: false,
        artisanEducation: false,
        CSNY: false,
        workerType:false
      },
      formData2: {
        sex: [
          {
            DICNAME: '男',
            key: '1',
          },
          {
            DICNAME: '女',
            key: '0',
          },
        ],
        artisanEducation: [
          {
            DICNAME: '初中及以下',
            key: 'artisanEducation',
          },
          {
            DICNAME: '高中',
            key: 'artisanEducation',
          },
          {
            DICNAME: '大专',
            key: 'artisanEducation',
          },
          {
            DICNAME: '本科',
            key: 'artisanEducation',
          },
          {
            DICNAME: '研究生',
            key: 'artisanEducation',
          },
        ],
        workerType:[
          {
            DICNAME: '测量放线',
            key: '测量放线',
          },
          {
            DICNAME: '钢筋加工安装',
            key: '钢筋加工安装',
          },
          {
            DICNAME: '砌筑抹灰',
            key: '砌筑抹灰',
          },
          {
            DICNAME: '混凝土拌制浇筑',
            key: '混凝土拌制浇筑',
          },
          {
            DICNAME: '木构件制作安装',
            key: '木构件制作安装',
          },
          {
            DICNAME: '模板安装拆卸',
            key: '模板安装拆卸',
          },

          {
            DICNAME: '脚手架安装拆卸',
            key: '脚手架安装拆卸',
          },
          {
            DICNAME: '防水防腐',
            key: '防水防腐',
          },
          {
            DICNAME: '水电安装',
            key: '水电安装',
          },
          {
            DICNAME: '金属焊接',
            key: '金属焊接',
          },
          {
            DICNAME: '管道制作安装',
            key: '管道制作安装',
          },
          {
            DICNAME: '中小型建筑机械操作',
            key: '中小型建筑机械操作',
          },
          {
            DICNAME: '综合',
            key: '综合',
          },
          {
            DICNAME: '其他',
            key: '其他',
          }
        ]
      },
      fileList: [],
      url: '',
      qitaShow:false,
      baseUrl: window.g.BaseURL,
      labelData: [
        {
          label: '工匠姓名',
          key: 'artisanName',
          isSelect: false,
          isread: true,
        },
        {
          label: '身份证号',
          key: 'idCard',
          isread: true,
        },
        {
          label: '联系电话',
          key: 'phone',
          isread: true,
        },
        {
          label: '性别',
          key: 'artisanSex',
          key1: 'sex',
          isSelect: false,
          isread: true,
        },
        {
          label: '出生年月',
          key: 'artisanBirthdate',
          key1: 'CSNY',
          isTime: false,
          isread: true,
        },
        {
          label: '文化程度',
          key: 'artisanEducation',
          key1: 'artisanEducation',
          isSelect: true,
          isread: true,
        },
        {
          label: '技能工种',
          key: 'isSkill',
          key1: 'isSkill',
          isSelect: true,
          isread: !this.iSadd,
        },
        {
          label: '注册区域',
          key: 'belongArea1',
          isSelect: true,
          isread: true,
          isread1: true,
        },
        {
          label: '从业年限',
          key: 'setYeare',
          isSelect: false,
          isread: !this.iSadd,
        },
        {
          label: '常住地址',
          key: 'contactAddress',
          isSelect: true,
          isread: true,
        },
        {
          label: '其他技能',
          key: 'otherSkill',
          isread:!this.qitaShow
        }
      ],
      //是否可选择
      iSadd: false,
      suID: '',
      data1:"",
      lable:""
    }
  },
  mounted() {
    //获取当前传过来的id 和 data
    this.iSadd = this.$route.query.id == '1' ? true : false
    console.log(this.iSadd,'hhhh')
    this.suID = this.$route.query.data
    if (ZWJSBridge) {
      ZWJSBridge.setTitle({
        title: '工匠个人信息',
      })
        .then((res) => {})
        .catch((err) => {})
    }
    this.getGJInformcion()
    this.getXianOpenDataView()
  },
  methods: {
    //获取上传的图片回显
    VantSelects(){
        console.log(this.$refs.selectMulPicker[0],'this.$refs.selectMulPicker')
        this.$refs.selectMulPicker && this.$refs.selectMulPicker[0].showPopu()
        this.$nextTick(() => {
             this.$refs.selectMulPicker[0].setDefaultValue(this.selectType) // 设置默认值
        })
    },
    async getPhoto(data1) {
      this.fileList = []
      // let data = res.data.data[0]
      this.url = 'api/upload/oss/preview?fileId=' + data1
      this.fileList.push({
        url: this.baseUrl + 'api/upload/oss/preview?fileId=' + data1,
        isImage: true,
      })
    },
    confirmMulSelect(data,data2){
        data.indexOf('其他')>-1?this.qitaShow = true:this.qitaShow = false
        if(data.indexOf('其他') == "-1"){
            this.formData.otherSkill = ''
        }
        this.formData.isSkill = data.toString()
        console.log(this.qitaShow)
    },
    //获取工匠信息
    async getGJInformcion() {
      let data = {
        accessCode: 'd6158bcf5e1c4a079375143b67b311f3',
        // appKey:"6738b790-69e8-11ec-a673-6805cab640a0",
        //cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        cityCode: '441300000000',
        id: window.localStorage.getItem('DanDianid') || '',
      }
      const res = await zhejiangHouseArtisan(data)
      if (!res.data.data) {
        this.formData.artisanName = window.localStorage.getItem('DanDianName')
        this.formData.phone = window.localStorage.getItem('DanDianPhone')
        this.formData.idCard = window.localStorage.getItem('DanDianid')
      } else {
        this.formData = res.data.data
        let newArr = this.formData.isSkill.split(',')
        if(newArr.length >0){
            newArr.forEach(item=>{
                if(item == '其他'){
                    this.qitaShow = true
                }
            })
        }
        if (this.formData.fileid) {
          this.getPhoto(this.formData.fileid)
        }
      }
      const str = idCard(window.localStorage.getItem('DanDianid'), 2)
      this.formData.artisanBirthdate = idCard(window.localStorage.getItem('DanDianid'), 1)
      console.log(str, '===================')
      this.formData.artisanSex = str
      this.formData.belongArea1 = this.formData.belongArea?this.formData.belongArea+'/'+this.formData.belongCountry:''
    },
    onConfirm1(value) {
      this.formData1[value.key] = false
      this.formData[value.key] = value.DICNAME
    },
    getXianOpenDataView: async function (data = '330000000000') {
      this.options = []
      const res = await getDatalistForTree(data)
      res.data.data.forEach((item) => {
        this.options.push({
          text: item.cityname,
          value: item.citycode,
          children: [],
        })
      })
      console.log(this.options, 'hezhilong')
      // this.options = res.data.data
    },
    handleChange(data) {
      this.lable = data
      this.IsShowAre = this.iSadd
    },
    onChange({ value, selectedOptions, tabIndex }) {
      if (selectedOptions[tabIndex].children.length == 0 && tabIndex < 1) {
        this.getXZQH(value, selectedOptions, tabIndex)
      }
      this.onFinish({ value, selectedOptions, tabIndex })
    },
    closeA() {
      this.IsShowAre = false
    },
    onFinish({ value, selectedOptions, tabIndex }) {
      if(this.lable == '注册区域'){
        this.formData.belongArea1 = selectedOptions.map((option) => option.text).join('/')
        if(tabIndex == 0){
          this.formData.belongArea = selectedOptions[tabIndex].text
        }
        // if(tabIndex == 1){
        //   this.formData.belongCountry = selectedOptions[tabIndex].text
        // }
        this.formData.citycode = selectedOptions[tabIndex].value
      }else{
        this.formData.contactAddress = selectedOptions.map((option) => option.text).join('/')
      }
      this.areaCode = selectedOptions.map((option) => option.value)
      this.areaCode.length == 2 ? (this.IsShowAre = false) : ''
    },
    getXZQH: async function (value, selectedOptions, tabIndex) {
      var res = await GetAdministrative(value)
      selectedOptions[tabIndex].children = []
      if (res.data.data.length > 0) {
        res.data.data.forEach((element) => {
          let obj = {
            text: element.cityname,
            value: element.citycode,
          }
          if (tabIndex < 1) {
            obj['children'] = []
          }
          selectedOptions[tabIndex].children.push(obj)
        })
      }
    },
    onConfirm2(value) {
      this.formData.CSNY = this.dateFormat(value)
      this.formData1.CSNY = false
    },
    // 格式化日期
    dateFormat(val) {
      let year = val.getFullYear()
      let month = val.getMonth() + 1
      let day = val.getDate()
      let hour = val.getHours()
      let minute = val.getMinutes()
      if (month >= 1 && month <= 9) {
        month = `0${month}`
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`
      }
      let time = `${year}-${month}-${day}`
      return time
    },
    isEmpty(obj) {
      if (typeof obj === 'undefined' || obj === null || obj === '' || obj === 'null') return true
      return false
    },
    preProcessData(data) {
      Object.keys(data).forEach((item) => {
        if (this.isEmpty(data[item])) {
          delete data[item]
        }
      })
      return data
    },
    async getinsertDataView(data) {
      this.formData = this.preProcessData(this.formData)
      var newobj = this.formData
      //判断必填项
      if(!this.formData.citycode || !this.formData.fileid){
        this.$toast.fail('请前往首页切换工匠选择个人信息维护模块修改完善工匠相关信息')
        return false
      }
      if (data == '修改' && this.$route.query.data1 != '竞赛资讯') {
        //只能修改
        let data1 = {
          idCard: window.localStorage.getItem('DanDianid'),
          trainEduId: this.suID,
          citycode:window.localStorage.getItem('citycodeChange')
              ? window.localStorage.getItem('citycodeChange')
              : '441300000000'
        }
        if (this.iSadd) {
          if(this.qitaShow){
            let newArr = this.formData.isSkill.split(',')
            let xiaobiao = newArr.indexOf('其他')
            newArr[xiaobiao] = this.formData.otherSkill
            this.formData.workerType = newArr.toString()
          }else {
            this.formData.workerType = this.formData.isSkill
          }
          data1 = { ...data1, ...this.formData }
        }
        const res = await zhejiangHouseTrainingEduBysubmit(data1)
        if (res.data.code == 200 && res.data.data&&res.data.msg=='SUCCESS') {
          this.$router.push({
            path: '/ZLJIndex',
          })
          this.$toast.success('报名成功!')
        } else {
          this.$toast.fail('您已报名成功')
        }
      } else {
        if (this.iSadd) {
          let data1 = {
            idCard: window.localStorage.getItem('DanDianid'),
            racePublicId: this.suID,
          }
          let newArr = this.formData.isSkill.split(',')
            let xiaobiao = newArr.indexOf('其他')
            newArr[xiaobiao] = this.formData.otherSkill
            this.formData.workerType = newArr.toString()
          data1 = { ...data1, ...this.formData }
          const res = await zhejiangHouseTrainingEduBysubmitJS(data1)
          if (res.data.code == 200 && res.data.data) {
            let date1 = timeFormat(null, 'yyyy-mm-dd hh:MM:ss')
            let data1 = {
              artisanCity: this.formData.contactAddress,
              artisanId: this.formData.id, //此字段必须
              artisanIdcard: this.formData.idCard,
              artisanName: this.formData.artisanName,
              artisanPhone: this.formData.phone,
              createDate: date1,
              racePublicId: this.suID, //此字段必须
            }
            const res = await zhejiangHouseArtisanRaceInfo(data1)
            if (res.data.code == 200) {
              this.$toast.success('报名成功')
              this.$router.push({
                path: '/ZLJIndex',
              })
            } else {
              this.$toast.fail('报名失败')
            }
          } else {
            this.$toast.fail(res.data.msg)
          }
        } else {
          let date1 = timeFormat(null, 'yyyy-mm-dd hh:MM:ss')
          console.log(this.$route.query.data,'djfue')
          debugger
          let data1 = {
            artisanCity: this.formData.contactAddress,
            artisanId: this.formData.id, //此字段必须
            artisanIdcard: this.formData.idCard,
            artisanName: this.formData.artisanName,
            artisanPhone: this.formData.phone,
            createDate: date1,
            racePublicId: this.suID, //此字段必须
          }
          const res = await zhejiangHouseArtisanRaceInfo(data1)
          if (res.data.code == 200&&res.data.msg == '保存成功' ) {
            this.$toast.success('报名成功')
            this.$router.push({
              path: '/ZLJIndex',
            })
          } else {
            this.$toast.fail('您已报名成功')
          }
        }
      }
    },
    afterRead(file) {
      this.getFileServerUpload(file.file, 'scsfz')
    },
    getFileServerUpload: async function (file, data) {
      let formData = new FormData()
      formData.append('files', file)
      formData.append('path', 'gj')
      formData.append('groupName', '工匠信息')
      formData.append('toGroupGuid', '123')
      const res = await ossUploadFiles(formData)
      let data2 = res.data.data
      console.log(data2, 'hezhilong')
      this.formData.fileid = data2[0].id
      if (this.formData.fileid) {
        this.$toast.success('上传成功!')
      }
    },
    delectFile: async function (file) {
      debugger
      try {
        let fileguid = ''
        if (file.ROW_GUID) {
          fileguid = file.ROW_GUID
        } else {
          fileguid = this.formData.fileid
        }
        this.url = ''
        console.log(fileguid, 'dkjfhui')
        if (fileguid) {
          let params = {
            accessCode: 'ce9b691634de4ebca68dc5bb638d07f4',
            cityCode: window.localStorage.getItem('citycode')
              ? window.localStorage.getItem('citycode')
              : '441300000000',
            params: {
              fileGuid: fileguid,
              token: window.localStorage.getItem('token'),
            },
          }
          const res = await FileServerProxy(params)
          let data = JSON.parse(res.data.data).Success
          if (data) {
            this.$toast.success('删除成功!')
          }
        }
      } catch (err) {
        this.$toast.success('删除成功!')
      }
    },
  },
  components:{
    vanSelect
  }
}
</script>
